package com.wanglibao.woodtrade.woodtrade.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.ItemBuyActivityAdapter;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.SupplyDetails;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.user.LoginActivity;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.SVGridView;

import butterknife.Bind;
import butterknife.ButterKnife;

/*
   供需信息界面中 我要买货的界面
 */
public class BuyActivity extends BaseActivity {


    @Bind(R.id.rl_contact_buy_activity)
    RelativeLayout rlContactBuyActivity;
    @Bind(R.id.tv_contact_title_buy_avtivity)
    TextView tvContactTitleBuyAvtivity;
    @Bind(R.id.ll_shanpinxiangqing_buy_activity)
    LinearLayout llShanpinxiangqingBuyActivity;
    @Bind(R.id.tv_introduction_buy_activity)
    TextView tvIntroductionBuyActivity;
    @Bind(R.id.ll_information_buy_activity)
    LinearLayout llInformationBuyActivity;
    @Bind(R.id.tv_activity_release_demand_type)
    TextView tvActivityReleaseDemandType;
    @Bind(R.id._activity_release_demand_size)
    TextView activityReleaseDemandSize;
    @Bind(R.id.edit_activity_release_demand_number)
    TextView editActivityReleaseDemandNumber;
    @Bind(R.id.edit_activity_release_demand_unit)
    TextView editActivityReleaseDemandUnit;
    @Bind(R.id.tv_activity_release_demand_moblie)
    TextView tvActivityReleaseDemandMoblie;
    @Bind(R.id.bt_contact_buy_avtivity)
    Button btContactBuyAvtivity;
    String type;

    @Bind(R.id.tv_shangpin_bianhao)
    LinearLayout TvShangpinBianhao;
    @Bind(R.id.tv_title_shangpin_bianhao)
    TextView TvTitleShangpinBianhao;
    @Bind(R.id.rv_editBuy_activity)
    SVGridView mRvEditBuyActivity;
    //========================================
    ItemBuyActivityAdapter mAdapter;
    SupplyDetails mDetails = null;

    Gson mGson = new Gson();
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 != 2) {
                mDetails = mGson.fromJson(msg.obj.toString(), SupplyDetails.class);
                appearData();
            }

            return false;
        }
    });
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        NetWorking();
        initData();
        mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public void NetWorking() {
        String id = getIntent().getStringExtra("ID");
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_MESSAGE,
                NetConfig.messageSendDetail, mHandler, "jsonObject", NetConfig.TaskId.messageSendDetail, new Object[]{id, 0});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    private void initData() {
        mBasIn = new BounceTopEnter();
        mBasOut = new SlideBottomExit();
        tvTitle.setText("求购详情");
        addViewClicklistener(btContactBuyAvtivity);

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        type = getIntent().getStringExtra("type");
    }

    public void appearData() {
        TvTitleShangpinBianhao.setText("商品编号："+mDetails.getNumbers());
        if(mDetails.getImg_ablum_list().size()>0){
            mAdapter=new ItemBuyActivityAdapter(this,mDetails.getImg_ablum_list());
            mRvEditBuyActivity.setAdapter(mAdapter);
        }
        tvContactTitleBuyAvtivity.setText(mDetails.getTitle());
        tvActivityReleaseDemandType.setText(mDetails.getCategory_name());
        editActivityReleaseDemandNumber.setText(mDetails.getNumber());
        activityReleaseDemandSize.setText(mDetails.getSize());
        editActivityReleaseDemandUnit.setText(mDetails.getWant_price());
        tvActivityReleaseDemandMoblie.setText(mDetails.getBuy_address_province_name() + "|" + mDetails.getBuy_address_city_name());
    }

    @Override
    public void onBackPressed() {
        if (TextUtils.isEmpty(type)){
            super.onBackPressed();
        }else{
            startActivity(new Intent(this,SupplyAndDemendActivity.class));
            finish();
            overridePendingTransition(R.anim.extre_in,R.anim.extre_out);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_contact_buy_avtivity:
                if (new UserImpl(this).isLogin()){
                    showDialog();
                }else{
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
        }
    }

    Dialog dialog;
    private void showDialog() {
        dialog = new Dialog(this, R.style.dialog_bgTransparent);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.getWindow().setContentView(R.layout.dialog_tel);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_dialog_title);
        tv_title.setText("请牢记单号并告知客服");
        TextView tv_contact = (TextView) dialog.findViewById(R.id.tv_dialog_contact);
        tv_contact.setText(mDetails.getNumbers());
        TextView tv_cancle = (TextView) dialog.findViewById(R.id.tv_dialog_tel_cancle);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tv_tel= (TextView) dialog.findViewById(R.id.tv_dialog_call);
        tv_tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mDetails != null) {
                    requestPermission();
                    final String forPhoneNum = mDetails.getPhone();
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + forPhoneNum));
                    startActivity(intent);
                }
            }
        });
    }
    /*操作权限的动态请求*/
    public void requestPermission() {
        //判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
                ToastUtil.createNormalToast("please give me the permission");
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 10);
            }
        } else {
        }
    }

    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;

    private void NormalDialogStyleTwo() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.content("订单号：" + mDetails.getNumber())//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(23)//
                .showAnim(mBasIn)//
                .dismissAnim(mBasOut)//
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        if (mDetails != null) {
                            final String forPhoneNum = mDetails.getPhone();
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.CALL");
                            intent.setData(Uri.parse("tel:" + forPhoneNum));
                            startActivity(intent);
                        }

                    }
                });
    }


}
